# coding: utf-8
import cgi
import os
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template

class Reading(db.Model):
    title = db.StringProperty(required=True)
    author = db.StringProperty()
    status = db.StringProperty(choices=set(['r','c','d']))
    user = db.UserProperty()
    date = db.DateTimeProperty(auto_now_add=True)
    def CountComments(self):
	comments = db.GqlQuery("SELECT * FROM Comment WHERE reading = :reading ORDER BY date DESC", reading = self.key()).count()
	return str(comments)
    def Complete(self):
        self.status = 'c' 
	self.put()
	return True
    def Delete(self):
        self.status = 'd' 
	self.put()
	return True

class Comment(db.Model):
    message = db.StringProperty(multiline=True)
    user = db.UserProperty()
    date = db.DateTimeProperty(auto_now_add=True)
    reading = db.ReferenceProperty(Reading)

class SaveReading(webapp.RequestHandler):
    def post(self):
        user = users.get_current_user()
        if user:
	    title = self.request.get('reading')
	    ref = self.request.get('ref')
	    if title=="":
		pass
	    else:
                reading = Reading(title=title)
                reading.user=user
                reading.status='r'
	    	reading.put()
	        self.response.out.write(reading.title)
     	    self.redirect('/'+ref)
        else:
            self.redirect(users.create_login_url(self.request.uri))

class SaveComment(webapp.RequestHandler):
    def post(self):
        comment = Comment()
        user = users.get_current_user()
        if user:
            comment.user=user
            comment.message = self.request.get('message')
            reading_key = self.request.get('reading')
	    reading = db.get(db.Key(reading_key))
            comment.reading = reading.key()
            comment.put()
            self.redirect('/comments/'+reading_key)
        else:
            self.redirect(users.create_login_url(self.request.uri))

class CompleteReading(webapp.RequestHandler):
    def get(self,reading_key):
        user = users.get_current_user()
        if user:
	    reading = db.get(db.Key(reading_key))
	    reading.Complete
            self.redirect('/list')
        else:
            self.redirect(users.create_login_url(self.request.uri))

class ListReading(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()
        if user:
	    query = db.GqlQuery("SELECT * FROM Reading WHERE user = :user "
                    "ORDER BY date DESC",
                    user = user)
	    readings = query.fetch(10)
	    template_values = {
		'readings' : readings,
            }
	    path = os.path.join(os.path.dirname(__file__), 'readings.html')
            self.response.out.write(template.render(path, template_values))
        else:
            self.redirect(users.create_login_url(self.request.uri))
	
class ListComments(webapp.RequestHandler):
    def get(self,reading_key):
        user = users.get_current_user()
	reading = db.get(db.Key(reading_key))
        query = db.GqlQuery("SELECT * FROM Comment WHERE reading = :reading "
                    "ORDER BY date DESC",
                    reading = reading.key())
        comments = query.fetch(10)

        if user:
		user_text="Comentar"
        else:
		user_text=""
	template_values = {
            'user_text': user_text,
	    'reading': reading,
	    'comments': comments,
        }
	path = os.path.join(os.path.dirname(__file__), 'comments.html')
        self.response.out.write(template.render(path, template_values))

class MainPage(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()
        if user:
	    user_text='Hola, ' + user.nickname() + ' - <a href="/list">Tus Lecturas</a> '
	    user_link=' - <a href="' + users.create_logout_url(self.request.uri) + '">Salir</a>'
	    nickname = user.nickname
        else:
	    user_link='<a href="' + users.create_login_url(self.request.uri) + '">Iniciar Sesi&oacute;n</a>'
	    nickname = 'guest'
	    user_text= ''
        readings = db.GqlQuery("SELECT * FROM Reading ORDER BY date DESC LIMIT 10")
	template_values = {
	    'user': nickname,
            'user_text': user_text,
            'user_link': user_link,
	    'readings': readings,
        }
	path = os.path.join(os.path.dirname(__file__), 'index.html')
        self.response.out.write(template.render(path, template_values))

application = webapp.WSGIApplication(
                                     [('/', MainPage),
                                     ('/save', SaveReading),
                                     ('/savecomment', SaveComment),
                                     ('/list', ListReading),
				     (r'/comments/(.*)', ListComments),
				     (r'/complete/(.*)', CompleteReading),
                                     ],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
